package com.allenyuan.carvingsocketclient;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class SocketStreamUtils {
	
	public static byte[] encode(com.google.protobuf.Message message) throws IOException {
		ByteArrayOutputStream byteOut = null;
		DataOutputStream dataOut = null;
		byte[] testArray = null;
		byte[] nameArray = null;
		
		testArray = message.toByteArray();
		nameArray = Arrays.copyOf(message.getDescriptorForType().getName().getBytes(), 255);
		byteOut = new ByteArrayOutputStream();
		dataOut = new DataOutputStream(byteOut);
		dataOut.write(nameArray);
		dataOut.writeInt(MessageTable.GetInstance().getIdByMessage(message));
		dataOut.writeInt(testArray.length);
		dataOut.write(testArray);
		dataOut.flush();
		return byteOut.toByteArray();
	}
	
	public static com.google.protobuf.Message decode(byte[] in) throws IOException {
		com.google.protobuf.Message message = null;
		ByteArrayInputStream byteIn = null;
		DataInputStream dataIn = null;
		byte[] nameArray = null;
		byte[] messageArray = null;
		
		if (in == null) {
			return message;
		}
		

		nameArray = new byte[255];
		int type = -1;
		int total_length = 0;
		int message_length = 0;

		total_length = in.length;
		byteIn = new ByteArrayInputStream(in, 0, total_length);
		dataIn = new DataInputStream(byteIn);
		dataIn.read(nameArray, 0, 255);
		type = dataIn.readInt();
		message_length = dataIn.readInt();
		messageArray = new byte[message_length];
		dataIn.read(messageArray, 0, message_length);
		
		message = MessageTable.GetInstance().getMessageById(type, messageArray);
		
		return message;
	}
}
